package handler

import (
	"net/http"
	"encoding/json"
)

type Global struct {
	ResponseWriter http.ResponseWriter
	Request *http.Request
}

func NewGlobal(w http.ResponseWriter, r *http.Request) *Global {
	g := new(Global)
	g.ResponseWriter = w
	g.Request = r
	//g.ResponseWriter.Header().Set("Content-Type", "application/json")
	//g.Header.Set("Content-Type", "application/json")
	return g
}

func (g *Global) SendJson(value interface{})  {
	g.ResponseWriter.Header().Set("Content-Type", "application/json")
	json.NewEncoder(g.ResponseWriter).Encode(value)
}

func (g *Global) WriteError(status int, err error)  {
	g.ResponseWriter.Header().Set("Content-Type", "application/json")
	g.ResponseWriter.WriteHeader(status)
	g.SendJson(map[string]interface{}{
		"status": status,
		"msg": err.Error(),
	})
}

func (g *Global) CheckErr(err error)  {
	if err != nil {
		g.NewError(500, err)
	}
}

func (g *Global) NewError(status int, err error)  {
	g.WriteError(status, err)
	panic(err)
}

func (g *Global) SendFile(file []byte)  {
	g.ResponseWriter.Write(file)
}